package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
	"html/template"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
)

type student struct {
	ID   uint   `db:"ID"`
	Name string `db:"Name"`
}

var db *sqlx.DB

func main() {
	var err error
	//链接数据库
	dsn := "root:chencheng233@tcp(127.0.0.1:3306)/go_test"
	db, err = sqlx.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	db.SetMaxOpenConns(100)
	db.SetMaxIdleConns(16)
	defer db.Close()

	router := gin.Default()
	// 前端页面传输数据到后端
	router.LoadHTMLFiles("templates/**/*")
	//设计页面的编码
	router.SetHTMLTemplate(template.Must(template.New("").Delims("[[", "]]").ParseGlob("templates/*.html")))

	router.POST("/submit", func(c *gin.Context) {
		name := c.PostForm("name")
		insertStudent(name)
		c.String(http.StatusOK, "数据已经写入数据库")
	})

	//从数据库中读取数据并回显到页面
	router.GET("/", func(c *gin.Context) {
		users := []student{}
		err := db.Select(&users, "SELECT ID, Name FROM student")
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(users)
		c.HTML(http.StatusOK, "index.html", gin.H{
			"users": users,
		})

	})
	router.Run(":8080")

}

func insertStudent(name string) {
	_, err := db.Exec("INSERT INTO student (Name) VALUES (?)", name)
	if err != nil {
		fmt.Println(err)
	}
}
